package com.ilancuo.java8;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Java 8 stream 方法
 */
public class StreamTest {
    public static void main(String[] args) {
//        test();
//        testFilter();
//        testForEach();
//        testMap();
//        testSorted();
//        testParallel();
//        testCollectors();
        testStats();
    }

    private static void testStats() {
        List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
        IntSummaryStatistics stat = numbers.stream().mapToInt(value -> value).summaryStatistics();
        System.out.println("列表中最大的数：" + stat.getMax());
        System.out.println("列表中最小的数：" + stat.getMin());
        System.out.println("所有数字之和：" + stat.getSum());
        System.out.println("平均数：" + stat.getAverage());
    }

    private static void testCollectors() {
        List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd", "jkl");
        List<String> filtered = strings.stream().filter(s -> !s.isEmpty()).collect(Collectors.toList());
        System.out.println("帅选列表：" + filtered);
        String mergedString = strings.stream().filter(s -> !s.isEmpty()).collect(Collectors.joining(", "));
        System.out.println("合并字符串：" + mergedString);
    }

    private static void testParallel() {
        List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd", "jkl");
        long count = strings.stream().filter(String::isEmpty).count();
        System.out.println(count);
    }

    private static void testSorted() {
        Random random = new Random();
        random.ints().limit(10).sorted().forEach(System.out::println);
    }

    private static void testMap() {
        List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
        List<Integer> squaresList = numbers.stream().map(i -> i * i).distinct().collect(Collectors.toList());
        System.out.println(squaresList);
    }

    private static void testForEach() {
        Random random = new Random();
        random.ints().limit(10).forEach(System.out::println);
    }

    private static void testFilter() {
        List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd", "jkl");
        List<String> filtered = strings.stream().filter(s -> !s.isEmpty()).collect(Collectors.toList());
        System.out.println(filtered);
    }

    private static void test() {
        List<Integer> integers = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            integers.add(i);
        }
        long count = integers.stream()
                .filter(integer -> integer % 2 == 0)
                .flatMap((Function<Integer, Stream<Integer>>) Stream::of)
                .peek(System.out::println)
                .limit(4)
                .count();
        System.out.println();
        System.out.println(count);
    }
}
